#!/usr/bin/env bash

if [[ $# -lt 1 ]]; then
    echo "Usage: $(basename $0) -d [directory] -o [outfile] -i [ignore pattern of .d path]"
    exit 1
fi

workdir="./"

outfile=""

ignore_pattern="scripts/|tools/"


while getopts "d:o:i:h" arg; do
    case $arg in
        d)
            workdir=$OPTARG
            ;;
        o)
            outfile=$OPTARG
            ;;
        i)
            ignore_pattern="${ignore_pattern}|${OPTARG}"
            ;;
        h)
            echo "Usage: $(basename $0) -d [directory] -o [outfile] -i [ignore pattern of .d path]"
            exit 127
            ;;
        *)
            echo "Unkonw argument"
            exit 1
            ;;
    esac
done

depfiles=$(find ${workdir} -name '.*.o.d' | grep -vE ${ignore_pattern})

if [ -z "${depfiles}" ]; then
    echo "no depfiles"
    exit 1
fi

if [ -z ${outfile} ]; then
    cat  ${depfiles}                        \
        | tr ' ' '\n'                       \
        | grep -v '\.o:' | grep -v '\-:' | grep -v '\\$'    \
        | sort -u
else
    echo "output to ${outfile}"
    cat  ${depfiles}                        \
        | tr ' ' '\n'                       \
        | grep -v '\.o:' | grep -v '\-:' | grep -v '\\$'    \
        | sort -u                           \
        > ${outfile}
fi

